/* eslint-disable no-undef */
import { observable, autorun, action, runInAction } from 'mobx';
import httpUtils from '../utils/http'

// var YuqueStore = observable({
//     loginUser: null, //登录的用户
//     repos: [], //用户的仓库列表
//     docs: [], //仓库对应的文档列表
//     getUsers() {
//         httpUtils.getFetch('/api/v2/user')
//             .then(res => {
//                 this.loginUser = res.data
//                 this.getUserRepos(res.data.id)
//             })
//             .catch(console.log)
//     },
//     getUserRepos(userId) {
//         httpUtils.getFetch(`/api/v2/users/${userId}/repos`)
//             .then(res => {
//                 this.repos = res.data
//             })
//             .catch(console.log)
//     },
//     getDocsByRepoId(repoId) {
//         httpUtils.getFetch(`/api/v2/repos/${repoId}/docs`)
//             .then(res => {
//                 const newIds = res.data.map(item => item.id)
//                 this.docs = (this.docs || []).filter(item => newIds.indexOf(item.id) == -1).push(...res.data)
//             })
//             .catch(console.log)
//     },
//     getFromRepo(repoId) {
//         return (this.docs || []).filter(item => item.book_id == repoId)
//     },
// })

// export default YuqueStore

class YuqueStore {
    @observable refreshing = true
    @observable loginUser = null
    @observable repos = null
    @observable docs = null

    constructor() {
        this.repos = []
        this.docs = {}
    }

    get avatarUrl() {
        return this.loginUser ? this.loginUser.small_avatar_url : ''
    }

    @action getUsers() {
        httpUtils.getFetch('/api/v2/user')
            .then(res => {
                this.loginUser = res.data
                // 异步拉取用户仓库的数据
                runInAction(this.getUserRepos(res.data.id))
            })
            .catch(console.log)
    }

    @action getUserRepos(userId) {
        this.refreshing = true
        httpUtils.getFetch(`/api/v2/users/${userId}/repos`)
            .then(res => {
                this.repos = res.data

                // 遍历拉取所有的文档
                res.data.forEach((repo) => {
                    this.getDocsByRepoId(repo.id)
                })
                this.refreshing = false
            })
            .catch(err => {
                console.log(err)
                this.refreshing = false
            })
    }

    @action getDocsByRepoId(repoId) {
        httpUtils.getFetch(`/api/v2/repos/${repoId}/docs`)
            .then(res => {
                this.docs = {
                    ...this.docs,
                    [`${repoId}`]: res.data,
                }
            })
            .catch(console.log)
    }
}
let yuqueStore = new YuqueStore()

/* 观察状态改变的函数 */
autorun(function () {
    console.log(
        `RepoLength = ${yuqueStore.repos.length}; Docs = ${yuqueStore.docs};`,
    );
}, { delay: 500 });

export default yuqueStore
